package com.gshrms.system.service.impl;

import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;
import javax.validation.Validator;
import javax.xml.crypto.Data;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.gshrms.common.core.domain.CommonResult;
import com.gshrms.common.core.domain.entity.SysRole;
import com.gshrms.common.core.domain.entity.SysUser;
import com.gshrms.system.domain.*;
import com.gshrms.system.domain.dto.AddSubAdminDto;
import com.gshrms.system.domain.dto.SetMasterAdminDto;
import com.gshrms.system.mapper.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import com.gshrms.common.annotation.DataScope;
import com.gshrms.common.constant.UserConstants;

import com.gshrms.common.exception.ServiceException;
import com.gshrms.common.utils.SecurityUtils;
import com.gshrms.common.utils.StringUtils;
import com.gshrms.common.utils.bean.BeanValidators;
import com.gshrms.common.utils.spring.SpringUtils;
import com.gshrms.system.service.ISysConfigService;
import com.gshrms.system.service.ISysDeptService;
import com.gshrms.system.service.ISysUserService;

/**
 * 用户 业务层处理
 *
 * @author ruoyi
 */
@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements ISysUserService {
    private static final Logger log = LoggerFactory.getLogger(SysUserServiceImpl.class);

    @Autowired
    private SysUserMapper userMapper;

    @Autowired
    private SysRoleMapper roleMapper;

    @Autowired
    private SysPostMapper postMapper;

    @Autowired
    private SysUserRoleMapper userRoleMapper;

    @Autowired
    private SysUserPostMapper userPostMapper;

    @Autowired
    private ISysConfigService configService;

    @Autowired
    private ISysDeptService deptService;

    @Autowired
    protected Validator validator;

    @Autowired
    private SysSubAdminMapper sysSubAdminMapper;
    @Autowired
    private SysUserMapper sysUserMapper;
    @Autowired
    private SysUserMenusMapper sysUserMenusMapper;

    /**
     * 根据条件分页查询用户列表
     *
     * @param user 用户信息
     * @return 用户信息集合信息
     */
    @Override
    @DataScope(deptAlias = "u", permission = "system:user:list")
    public List<SysUser> selectUserList(SysUser user) {
        return userMapper.selectUserList(user);
    }

    /**
     * 根据条件分页查询已分配用户角色列表
     *
     * @param user 用户信息
     * @return 用户信息集合信息
     */
    @Override
    @DataScope(deptAlias = "u", permission = "system:user:list")
    public List<SysUser> selectAllocatedList(SysUser user) {
        return userMapper.selectAllocatedList(user);
    }

    /**
     * 根据条件分页查询未分配用户角色列表
     *
     * @param user 用户信息
     * @return 用户信息集合信息
     */
    @Override
    @DataScope(deptAlias = "u", permission = "system:user:list")
    public List<SysUser> selectUnallocatedList(SysUser user) {
        return userMapper.selectUnallocatedList(user);
    }

    /**
     * 通过用户名查询用户
     *
     * @param userName 用户名
     * @return 用户对象信息
     */
    @Override
    public SysUser selectUserByUserName(String userName) {
        return userMapper.selectUserByUserName(userName);
    }

    /**
     * 通过用户ID查询用户
     *
     * @param userId 用户ID
     * @return 用户对象信息
     */
    @Override
    public SysUser selectUserById(Long userId) {
        return userMapper.selectUserById(userId);
    }

    /**
     * 查询用户所属角色组
     *
     * @param userName 用户名
     * @return 结果
     */
    @Override
    public String selectUserRoleGroup(String userName) {
        List<SysRole> list = roleMapper.selectRolesByUserName(userName);
        if (CollectionUtils.isEmpty(list)) {
            return StringUtils.EMPTY;
        }
        return list.stream().map(SysRole::getRoleName).collect(Collectors.joining(","));
    }

    /**
     * 查询用户所属岗位组
     *
     * @param userName 用户名
     * @return 结果
     */
    @Override
    public String selectUserPostGroup(String userName) {
        List<SysPost> list = postMapper.selectPostsByUserName(userName);
        if (CollectionUtils.isEmpty(list)) {
            return StringUtils.EMPTY;
        }
        return list.stream().map(SysPost::getPostName).collect(Collectors.joining(","));
    }

    /**
     * 校验用户名称是否唯一
     *
     * @param user 用户信息
     * @return 结果
     */
    @Override
    public boolean checkUserNameUnique(SysUser user) {
        Long userId = StringUtils.isNull(user.getUserId()) ? -1L : user.getUserId();
        SysUser info = userMapper.checkUserNameUnique(user.getUserName());
        if (StringUtils.isNotNull(info) && info.getUserId().longValue() != userId.longValue()) {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    /**
     * 校验手机号码是否唯一
     *
     * @param user 用户信息
     * @return
     */
    @Override
    public boolean checkPhoneUnique(SysUser user) {
        Long userId = StringUtils.isNull(user.getUserId()) ? -1L : user.getUserId();
        SysUser info = userMapper.checkPhoneUnique(user.getPhonenumber());
        if (StringUtils.isNotNull(info) && info.getUserId().longValue() != userId.longValue()) {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    /**
     * 新增保存用户信息
     *
     * @param user 用户信息
     * @return 结果
     */
    @Override
    @Transactional
    public int insertUser(SysUser user) {
        // 新增用户信息
        int rows = userMapper.insertUser(user);
        return rows;
    }

    /**
     * 注册用户信息
     *
     * @param user 用户信息
     * @return 结果
     */
    @Override
    public boolean registerUser(SysUser user) {
        return userMapper.insertUser(user) > 0;
    }

    /**
     * 修改保存用户信息
     *
     * @param user 用户信息
     * @return 结果
     */
    @Override
    @Transactional
    public int updateUser(SysUser user) {
        Long userId = user.getUserId();
        // 删除用户与角色关联
        userRoleMapper.deleteUserRoleByUserId(userId);
        // 新增用户与角色管理
        // 删除用户与岗位关联
        userPostMapper.deleteUserPostByUserId(userId);
        // 新增用户与岗位管理
        return userMapper.updateUser(user);
    }

    /**
     * 用户授权角色
     *
     * @param userId  用户ID
     * @param roleIds 角色组
     */
    @Override
    @Transactional
    public void insertUserAuth(Long userId, Long[] roleIds) {
        userRoleMapper.deleteUserRoleByUserId(userId);
        insertUserRole(userId, roleIds);
    }

    /**
     * 修改用户状态
     *
     * @param user 用户信息
     * @return 结果
     */
    @Override
    public int updateUserStatus(SysUser user) {
        return userMapper.updateUser(user);
    }

    /**
     * 修改用户基本信息
     *
     * @param user 用户信息
     * @return 结果
     */
    @Override
    public int updateUserProfile(SysUser user) {
        return userMapper.updateUser(user);
    }

    /**
     * 修改用户头像
     *
     * @param userName 用户名
     * @param avatar   头像地址
     * @return 结果
     */
    @Override
    public boolean updateUserAvatar(String userName, String avatar) {
        return userMapper.updateUserAvatar(userName, avatar) > 0;
    }

    /**
     * 重置用户密码
     *
     * @param user 用户信息
     * @return 结果
     */
    @Override
    public int resetPwd(SysUser user) {
        return userMapper.updateUser(user);
    }

    /**
     * 重置用户密码
     *
     * @param userName 用户名
     * @param password 密码
     * @return 结果
     */
    @Override
    public int resetUserPwd(String userName, String password) {
        return userMapper.resetUserPwd(userName, password);
    }


    /**
     * 新增用户角色信息
     *
     * @param userId  用户ID
     * @param roleIds 角色组
     */
    public void insertUserRole(Long userId, Long[] roleIds) {
        if (StringUtils.isNotEmpty(roleIds)) {
            // 新增用户与角色管理
            List<SysUserRole> list = new ArrayList<SysUserRole>(roleIds.length);
            for (Long roleId : roleIds) {
                SysUserRole ur = new SysUserRole();
                ur.setUserId(userId);
                ur.setRoleId(roleId);
                list.add(ur);
            }
            userRoleMapper.batchUserRole(list);
        }
    }

    /**
     * 通过用户ID删除用户
     *
     * @param userId 用户ID
     * @return 结果
     */
    @Override
    @Transactional
    public int deleteUserById(Long userId) {
        // 删除用户与角色关联
        userRoleMapper.deleteUserRoleByUserId(userId);
        // 删除用户与岗位表
        userPostMapper.deleteUserPostByUserId(userId);
        return userMapper.deleteUserById(userId);
    }

    @Override
    public int deleteUserByIds(Long[] userIds) {
        return 0;
    }


    /**
     * 导入用户数据
     *
     * @param userList        用户数据列表
     * @param isUpdateSupport 是否更新支持，如果已存在，则进行更新数据
     * @param operName        操作用户
     * @return 结果
     */
    @Override
    public String importUser(List<SysUser> userList, Boolean isUpdateSupport, String operName) {
        if (StringUtils.isNull(userList) || userList.size() == 0) {
            throw new ServiceException("导入用户数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        for (SysUser user : userList) {
            try {
                // 验证是否存在这个用户
                SysUser u = userMapper.selectUserByUserName(user.getUserName());
                if (StringUtils.isNull(u)) {
                    BeanValidators.validateWithException(validator, user);
                    deptService.checkDeptDataScope(user.getDeptId());
                    String password = configService.selectConfigByKey("sys.user.initPassword");
                    user.setPassword(SecurityUtils.encryptPassword(password));
                    user.setCreateBy(operName);
                    userMapper.insertUser(user);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、账号 " + user.getUserName() + " 导入成功");
                } else if (isUpdateSupport) {
                    BeanValidators.validateWithException(validator, user);
                    deptService.checkDeptDataScope(user.getDeptId());
                    user.setUserId(u.getUserId());
                    user.setUpdateBy(operName);
                    userMapper.updateUser(user);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、账号 " + user.getUserName() + " 更新成功");
                } else {
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、账号 " + user.getUserName() + " 已存在");
                }
            } catch (Exception e) {
                failureNum++;
                String msg = "<br/>" + failureNum + "、账号 " + user.getUserName() + " 导入失败：";
                failureMsg.append(msg + e.getMessage());
                log.error(msg, e);
            }
        }
        if (failureNum > 0) {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new ServiceException(failureMsg.toString());
        } else {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }


    /**
     * 设置/取消 用户主管理员
     *
     * @param setMasterAdminDto
     * @return
     */
    @Override
    public CommonResult setMasterAdmin(SetMasterAdminDto setMasterAdminDto) {
        SysUser sysUser = new SysUser();
        BeanUtils.copyProperties(setMasterAdminDto, sysUser);
        sysUser.setUpdateBy(SecurityUtils.getUsername());
        int i = userMapper.updateUser(sysUser);
        return CommonResult.resultVoid(i, "操作");
    }

    /**
     * 添加子管理员
     *
     * @param sysSubAdmin
     * @return
     */
    @Override
    @Transactional
    public CommonResult addSubAdmin(SysSubAdmin sysSubAdmin) throws JsonProcessingException {
        //新增管理组
        int w = 0;
        sysSubAdmin.setCreateTime(LocalDateTime.now());
        sysSubAdmin.setCreateUser(SecurityUtils.getUserId().toString());
        w = sysSubAdminMapper.insert(sysSubAdmin);
        List<AddSubAdminDto> addSubAdminDtos = sysSubAdmin.getAddSubAdminDtos();
        for (int i = 0; i < addSubAdminDtos.size(); i++) {
            //将选择的用户设置为子管理员
            AddSubAdminDto addSubAdminDto = addSubAdminDtos.get(i);
            Long userId = addSubAdminDto.getUserId();
            SysUser sysUser = new SysUser();
            sysUser.setUserId(userId);
            sysUser.setUserType("02");
            w = userMapper.updateById(sysUser);
            //添加用户对应的管理组菜单id和权限id到关联表
            for (int q = 0; q < addSubAdminDto.getMenuIds().size(); q++) {
                SysUserMenus sysUserMenus = new SysUserMenus();
                sysUserMenus.setUserId(userId);
                sysUserMenus.setMenuId(addSubAdminDto.getMenuIds().get(q));
                sysUserMenus.setGmId(sysSubAdmin.getGmId());
                Set<Long> orgIds = addSubAdminDto.getOrgIds();
                ObjectMapper objectMapper = new ObjectMapper();
                String jsonAuthorities = objectMapper.writeValueAsString(orgIds);
                sysUserMenus.setAuthorityLimit(jsonAuthorities);
                w = sysUserMenusMapper.insert(sysUserMenus);
            }
        }
        return CommonResult.resultVoid(w, "操作");
    }


    /**
     * 编辑子管理员
     *
     * @param sysSubAdmin
     * @return
     */
    @Override
    public CommonResult updateSubAdmin(SysSubAdmin sysSubAdmin) throws JsonProcessingException {
        int w = 0;
        //修改管理组信息
        sysSubAdmin.setUpdateTime(LocalDateTime.now());
        sysSubAdmin.setUpdateUser(SecurityUtils.getUserId().toString());
        w = sysSubAdminMapper.updateById(sysSubAdmin);

        //查询出此管理组下有哪些用户
        List<SysUser> users = sysSubAdminMapper.selectUserListBySubAdmin(sysSubAdmin.getGmId());
        //将这些用户修改为普通用户
        for (SysUser user : users) {
            user.setUserType("00");
            user.setUpdateBy(SecurityUtils.getUsername());
            user.setUpdateTime(new Date());
            sysUserMapper.updateById(user);
        }

        //将管理组原本关联的用户和菜单删除
        LambdaQueryWrapper<SysUserMenus> userMenusLambdaQueryWrapper = new LambdaQueryWrapper<>();
        userMenusLambdaQueryWrapper.eq(SysUserMenus::getGmId, sysSubAdmin.getGmId());
        w = sysUserMenusMapper.delete(userMenusLambdaQueryWrapper);

        List<AddSubAdminDto> addSubAdminDtos = sysSubAdmin.getAddSubAdminDtos();
        for (int i = 0; i < addSubAdminDtos.size(); i++) {
            //将选择的用户设置为子管理员
            AddSubAdminDto addSubAdminDto = addSubAdminDtos.get(i);
            Long userId = addSubAdminDto.getUserId();
            SysUser sysUser = new SysUser();
            sysUser.setUserId(userId);
            sysUser.setUserType("02");
            w = userMapper.updateById(sysUser);
            //添加用户对应的管理组菜单id和权限id到关联表
            for (int q = 0; q < addSubAdminDto.getMenuIds().size(); q++) {
                SysUserMenus sysUserMenus = new SysUserMenus();
                sysUserMenus.setUserId(userId);
                sysUserMenus.setMenuId(addSubAdminDto.getMenuIds().get(q));
                sysUserMenus.setGmId(sysSubAdmin.getGmId());
                Set<Long> orgIds = addSubAdminDto.getOrgIds();
                ObjectMapper objectMapper = new ObjectMapper();
                String jsonAuthorities = objectMapper.writeValueAsString(orgIds);
                sysUserMenus.setAuthorityLimit(jsonAuthorities);
                w = sysUserMenusMapper.insert(sysUserMenus);
            }
        }
        return CommonResult.resultVoid(w, "操作");
    }


    /**
     * 删除子管理员管理组
     *
     * @param gmId
     * @return
     */
    @Override
    @Transactional
    public CommonResult deleteSubAdmin(Long gmId) {
        int w = 0;
        //查询出此管理组下有哪些用户
        List<SysUser> users = sysSubAdminMapper.selectUserListBySubAdmin(gmId);
        //将这些用户修改为普通用户
        for (SysUser user : users) {
            user.setUserType("00");
            user.setUpdateBy(SecurityUtils.getUsername());
            user.setUpdateTime(new Date());
            sysUserMapper.updateById(user);
        }
        //将管理组关联的用户和菜单删除
        LambdaQueryWrapper<SysUserMenus> userMenusLambdaQueryWrapper = new LambdaQueryWrapper<>();
        userMenusLambdaQueryWrapper.eq(SysUserMenus::getGmId, gmId);
        w = sysUserMenusMapper.delete(userMenusLambdaQueryWrapper);

        //删除管理组
        w = sysSubAdminMapper.deleteById(gmId);
        return CommonResult.resultVoid(w, "删除");
    }
}
